<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="80%">
    <el-form class="handleform" :disabled="disabledHead" ref="handleform" :rules="rules"  :model="head" size="small" label-width="100px">
    	<el-row>
        <el-col :span="5">
        	<el-form-item label="单位名称" prop="entrustOrganizationId" >
            <entrustSelect :eid.sync="head.entrustOrganizationId" @change="upEid" :name="head.organizationName"></entrustSelect>
        	</el-form-item>
        </el-col>
        <el-col :span="8">
        	<el-form-item label="监测日期" prop="beginTime">
            <!-- <my-time-picker
              :start-time.sync="head.beginTime"
              :end-time.sync="head.endTime"
              placeholder="检测"
            >
            </my-time-picker> -->
            <my-auto-time-picker
              :start-time.sync="head.beginTime"
              :end-time.sync="head.endTime"
              :config="{
                type: 'year',
                num: 1
              }"
            >
            </my-auto-time-picker>
        	</el-form-item>
        </el-col>
        <el-col :span="5">
        	<el-form-item label="仪器名称">
        		<el-input
        			v-model="head.equipmentName"
        			disabled
        		/>
        	</el-form-item>
        </el-col>
        <el-col :span="5">
        	<el-form-item label="仪器型号">
        		<el-input
        			v-model="head.equipmentTypeNumber"
        			disabled
        		/>
        	</el-form-item>
        </el-col>
    	</el-row>
    	<el-row>
        <el-col :span="5">
        	<el-form-item label="仪器编号">
        		<el-input
        			v-model="head.equipmentNumber"
        			disabled
        		/>
        	</el-form-item>
        </el-col>
        <el-col :span="13">
        	<el-form-item label="单位地址">
        		<el-input
        			v-model="head.organizationAddress"
        			disabled
        		/>
        	</el-form-item>
        </el-col>
    	</el-row>
    </el-form>
    <el-divider></el-divider>
    <el-form class="handleform"  :model="queryParams" :rules="rules" size="small" label-width="100px" >
    	<el-row >
    		<el-col :span="5">
    			<el-form-item label="年份" prop="year">
    			  <el-date-picker
              v-model="date"
              type="year"
              :clearable="false"
              :disabled="type != 'add'"
              placeholder="选择年">
    			  </el-date-picker>
    			</el-form-item>
    		</el-col>
        <el-col :span="4">
          <el-form-item label="文件查看" :class="this.head.recordOssId || this.head.reportOssId ? '':'hidden'">
            <div style="width: 100%;justify-content: space-around;align-items: center;display: flex;">
              <el-link type="primary" v-show="head.recordOssId" @click="viewFile(head.recordOssId)">记录</el-link>
              <el-link type="primary" v-show="head.reportOssId" @click="viewFile(head.reportOssId)">报告</el-link>
              <el-link type="primary" v-show="head.annualStatisticsOssId" @click="viewFile(head.annualStatisticsOssId)">年度报告</el-link>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="15" v-show="type=='handle' && this.id">
          <div style="display: flex;justify-content: right;">
            <el-button type="primary"  size="mini" @click.native.prevent="handle('year')">生成年度报告</el-button>
            <el-button type="primary"  size="mini" @click.native.prevent="handle('record')">生成记录</el-button>
            <el-button type="primary"  size="mini" @click.native.prevent="handle('report')">生成报告</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>

    <el-table class="handletabel"
    	ref="tableData"
    	v-loading="loading"
    	:data="dataList"
    	height="364"
			:cell-class-name="tableCellClassName"
      @row-dblclick="handleDbTable"
    >
    <el-table-column label="剂量计编号" align="center" prop="dosageNumber" />
    <el-table-column label="姓名" align="center" prop="personnelName" />
    <el-table-column label="性别" align="center" prop="personnelSex" >
      <template slot-scope="scope">
        <dict-tag :value="scope.row.personnelSex" :options = "dict.type.sys_user_sex">
        </dict-tag>
      </template>
    </el-table-column>
    <el-table-column label="职业类别" align="center" prop="occupationalClassificationName" >
      <template slot-scope="scope">
        {{scope.row.occupationalClassificationName}}
      </template>
    </el-table-column>
    <el-table-column label="监测周期" align="center">
      <el-table-column label="第一批次(mSv)" align="center" prop="value1" >
        <template slot-scope="{ row, $index }">
          <el-input
            v-if="row.isAddStr === 'value1'"
            :ref="`value1_${$index}`"
            v-model="row.value1"
            size="mini"
            @change="val => handleChangeValue(val, row, $index, 'value1')"
            @blur="val => handleChangeClose(val, row)"
          />
          <span v-else>{{ row.value1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="第二批次(mSv)" align="center" prop="value2" >
        <template slot-scope="{ row, $index }">
          <el-input
            v-if="row.isAddStr === 'value2'"
            :ref="`value2_${$index}`"
            v-model="row.value2"
            size="mini"
            @change="val => handleChangeValue(val, row, $index, 'value2')"
            @blur="val => handleChangeClose(val, row)"
          />
          <span v-else>{{ row.value2 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="第三批次(mSv)" align="center" prop="value3" >
        <template slot-scope="{ row, $index }">
          <el-input
            v-if="row.isAddStr === 'value3'"
            :ref="`value3_${$index}`"
            v-model="row.value3"
            size="mini"
            @change="val => handleChangeValue(val, row, $index, 'value3')"
            @blur="val => handleChangeClose(val, row)"
          />
          <span v-else>{{ row.value3 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="第四批次(mSv)" align="center" prop="value4" >
        <template slot-scope="{ row, $index }">
          <el-input
            v-if="row.isAddStr === 'value4'"
            :ref="`value4_${$index}`"
            v-model="row.value4"
            size="mini"
            @change="val => handleChangeValue(val, row, $index, 'value4')"
            @blur="val => handleChangeClose(val, row)"
          />
          <span v-else>{{ row.value4 }}</span>
        </template>
      </el-table-column>
    </el-table-column>
    <el-table-column label="剂量当量总和" align="center" prop="dosageValue" >
      <template slot="header">
        <div>剂量当量 Hp(10)</div>
      </template>
    </el-table-column>
    </el-table>
    <div>
      <pagination
      	:total="total"
      	:page.sync="page.pageNum"
      	:limit.sync="page.pageSize"
        hide-on-single-page
      	@pagination="getList()"
      />
    </div>

		<!-- 意见弹框 -->
		<el-dialog
			title="审批意见"
			:visible.sync="manageVisible"
			:close-on-click-modal="false"
			width="600px"
      append-to-body
			v-dialogDrag="true"
		>
			<el-input
				v-model="manageForm.comment"
				type="textarea"
				placeholder="请输入审批意见"
				clearable
			/>
			<div slot="footer">
				<el-button type="primary" @click="submitManageData">确 定</el-button>
			</div>
		</el-dialog>
    <template slot="footer" class="dialog-footer">
      <el-button @click="addTask" v-show="type== 'add'" type="primary">添加</el-button>
      <el-button @click="handleTask(1)" v-show="type== 'handle'" type="primary" style="margin-right: 20px;">办理</el-button>
      <el-button @click="handleTask(2)" v-show="type== 'handle'" type="warning" style="margin-right: 20px;">驳回</el-button>
      <el-button @click="close">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { getAnnualDoseInfo,getAnnualDoseInfoRecords,addTask,getAnnualDoseInfoById,record,handleRecord,handleReport,handle, handleYearReport } from "@/api/slides/annualdose";
  import { listByIds} from "@/api/system/oss";
  import entrustSelect from '@/components/select/src/entrustSelect'
  export default{
    name:"annualdoseDialog",
    dicts:['sys_user_sex'],
    components:{entrustSelect},
    data(){
      return {
        dialogVisible:false,
        title:'年度个人剂量详情',
        queryParams:{
          entrustOrganizationId:null,
          year:null,
        },
        page:{
          pageNum:1,
          pageSize:1000
        },
        watchFlag:false,
        rules:{
          year:[
            { required: true, message: '请选择年份'}
          ],
          entrustOrganizationId:[
            {required: true, message: '请选择单位'}
          ],
          reportNumber:[
            { required: true, message: '请输入报告编号' }
          ],
          beginTime:[
            { required: true, message: '请选择监测日期' }
          ]
        },
        type:'add',
        head:{
        },
        headCache:{
          beginTime:undefined,
          endTime:undefined
        },
        id:null,
        dataList:[],
        loading:false,
        total:0,
        manageForm: {},
        manageVisible: false
      }
    },
    watch:{
      queryParams:{
        handler(val){
          if(this.watchFlag && this.type == 'add'){
            this.selectDate()
          }
        },
        deep:true
      }
    },
    computed:{
      date:{
        get(){
          return this.parseTime(new Date(this.queryParams.year + '-01-01'), '{y}');
        },
        set(val){
          this.queryParams.year = val.getFullYear()
        }
      },
      monitoringDate:{
        get(){
          return [this.head.beginTime,this.head.endTime]
        },
        set(val){
          this.head.beginTime = val[0]
          this.head.endTime = val[1]
        }
      },
      disabledHead(){
        return this.type == 'view'
      }
    },
    methods:{
      upEid(val){
        console.log('val',val);
        this.head.entrustOrganizationId = this.queryParams.entrustOrganizationId = val.entrustOrganizationId
        this.head.organizationName = val.organizationName
      },
      // 报告预览
      viewFile(ossId) {
        listByIds(ossId).then((response) => {
          window.open(response?.data[0]?.url, 'PDF','');
        });
      },
      handleYearReport() {

      },
      // 给单元格绑定横向和竖向的index，这样就能确定是哪一个单元格
      tableCellClassName({row, column, rowIndex, columnIndex}){
        row.index = rowIndex;
        column.index = columnIndex;
      },
      handleDbTable(row, column, event) {
        if (this.head.tasksState != 0) {
          return
        }
        this.$set(row, 'isAddStr', column.property)
        const str = `${column.property}_${row.index}`
        this.$nextTick(res => {
          if (this.$refs[str]) {
            this.$refs[str].focus()
          }
        })
      },
      /**
       * 修改批次值
       * @param val 修改值
       * @param row 数据
       * @param index 下标
       * @param valStr 需要修改字段名
       */
      handleChangeValue(val, row, index, valStr) {
        console.log(row);
        const num = parseFloat(
          new this.big(row?.value1 || 0).plus(row?.value2 || 0).plus(row?.value3 || 0).plus(row?.value4 || 0)
        )
        this.$set(row, 'dosageValue', num)
        // console.log(val, row, index, valStr, num);
      },
      // 关闭修改
      handleChangeClose(val, row) {
        this.$set(row, 'isAddStr', '')
      },
      //生成报告或记录
      handle(type){
        this.watchFlag = false;
        let req = type == 'report' ? handleReport(this.id) : type == 'record' ? handleRecord(this.id) : handleYearReport({id: this.id})
        req.then(res=>{
          this.$message({
            message:'生成成功',
            type:"success"
          })
          this.selectDateById()
        })
      },
      submitManageData() {
        // return
        handle(this.manageForm).then((response) => {
            this.manageVisible = false
            this.manageForm = {}
            this.$modal.msgSuccess("处理成功");
            this.close()
        });
      },
      //办理任务
      handleTask(operation){
        this.manageVisible = true
        this.head.taskAnnualDoseInfoRecordList = this.dataList
				this.manageForm = {
          operation,
          taskAnnualDose: this.head,
        }

        // handle({id:this.id,operation}).then(res=>{
        //   this.$message({
        //     message:"处理成功",
        //     type:'success'
        //   })
        //   this.close()
        // })
      },
      //添加任务
      addTask(){
        console.log(this.head);
        this.$refs['handleform'].validate(valid=>{
          if(valid){
            this.head.year = this.queryParams.year
            this.head.taskAnnualDoseInfoRecordList = this.dataList
            addTask(this.head).then(res=>{
              this.$message({
                'message':'添加成功',
                'type':'success'
              })
              this.close()
            })
          }
        })
      },
      open(id,type){
        this.type = type
        this.resetParams()
        if(id){
          this.id = id
          this.selectDateById()
        }else{
          this.watchFlag = true
        }
        this.dialogVisible = true
      },
      close(){
        this.watchFlag = false
        this.$emit('close')
        this.dialogVisible = false
      },
      resetParams(){
        this.queryParams = {
          year : new Date().getFullYear()-1,
          entrustOrganizationId:null
        }
        this.dataList = []
        this.head = this.headCache
        this.total = 0
      },
      selectDateById(){
        this.getHead(this.id)
        this.getList(this.id)
      },
      selectDate(){
        if(this.queryParams.entrustOrganizationId ){
          this.getHead()
          this.getList()
        }
      },
      getHead(id = null){
        let req = id ? getAnnualDoseInfoById(id) : getAnnualDoseInfo(this.queryParams)
        req.then(res=>{
          this.head = res.data || this.headCache
          this.head.tasksState = this.head.tasksState || 0
          if(!res.data){
            this.$message({
              message: '暂无历史数据',
              type: 'warning'
            });
          }
          if(id){
            this.queryParams = {
              year : res.data.year,
              entrustOrganizationId:res.data.entrustOrganizationId
            }
            this.$nextTick(()=>{
              setTimeout(()=>{
                this.watchFlag = true;
              },800)
            })
          }
        })
      },
      getList(id = null){
        this.loading = true
        let req = id ? record({id, ...this.page}) : getAnnualDoseInfoRecords({...this.queryParams,...this.page})
        req.then(res=>{
          this.dataList = res.rows || []
          this.total = res.total
        }).finally(()=>{
          this.loading = false
        })
      }
    }
  }
</script>

<style lang="scss">
  .el-divider--horizontal{
    margin: 12px;
  }
  .hidden{
    visibility: hidden;
  }
</style>
